import client from "../db/client.ts"
// config
import { TABLE } from "../db/config.ts"
// Interface
import Todo from "../interfaces/Todo.ts"

export default {
  /**
   * 检查id是否存在
   * @param id
   * @returns 数据表中是否有此数据
   */
  doesExistById: async ({ id }: Todo) => {
    const [result] = await client.query(
      `SELECT COUNT(*) count FROM ${TABLE.TODO} WHERE id = ? LIMIT 1`,
      [id]
    )
    return result.count > 0
  },
  /**
   * 返回 todo 表的所有数据
   * @returns array of todos
   */
  getAll: async () => {
    return await client.query(`SELECT * FROM ${TABLE.TODO}`)
  },
  /**
   * 返回指定id的数据
   * @param id
   * @returns object of todo item
   */
  getById: async ({ id }: Todo) => {
    return await client.query(`SELECT * FROM ${TABLE.TODO} WHERE id = ?`, [id])
  },
  /**
   * 新增一个todo
   * @param todo
   * @param isCompleted
   */
  add: async ({ todo, isCompleted }: Todo) => {
    return await client.query(
      `INSERT INTO ${TABLE.TODO}(todo, isCompleted) values(?, ?)`,
      [todo, isCompleted]
    )
  },
  /**
   * 更新指定id的todo
   * @param id
   * @param todo
   * @param isCompleted
   * @returns 返回一个整数，代表影响的行数
   */
  updateById: async ({ id, todo, isCompleted = false }: Todo) => {
    const result = await client.query(
      `UPDATE ${TABLE.TODO} SET todo=?, isCompleted=? WHERE id=?`,
      [todo, isCompleted, id]
    )
    // 返回更新的行数
    return result.affectedRows
  },
  /**
   * 删除一个指定id的todo
   * @param id
   * @returns 返回一个整数，代表影响的行数
   */
  deleteById: async ({ id }: Todo) => {
    const result = await client.query(
      `DELETE FROM ${TABLE.TODO} WHERE id = ?`,
      [id]
    )
    // 返回更新的行数
    return result.affectedRows
  }
}
